<template>
  <div class="dashboard-page">
    <div class="breadcrumb">
      <el-breadcrumb separator=">">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-alert
        :title="welcomeMessage"
        type="success"
        :closable="false"
        show-icon
        class="welcome-alert"
    />

    <el-row :gutter="20" class="stat-cards" v-loading="statisticsLoading">
      <el-col :span="6">
        <el-card shadow="never" class="stat-card" style="--card-bg: #20c997;">
          <div class="card-content">
            <div class="icon-wrapper">
              <el-icon><User /></el-icon>
            </div>
            <div class="text-wrapper">
              <div class="stat-number">{{ statistics.userCount || 0 }}</div>
              <div class="stat-label">商城用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="never" class="stat-card" style="--card-bg: #fd7e14;">
          <div class="card-content">
            <div class="icon-wrapper">
              <el-icon><PriceTag /></el-icon>
            </div>
            <div class="text-wrapper">
              <div class="stat-number">{{ statistics.productCount || 0 }}</div>
              <div class="stat-label">商品种类</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="never" class="stat-card" style="--card-bg: #ffc107;">
          <div class="card-content">
            <div class="icon-wrapper">
              <el-icon><ShoppingCart /></el-icon>
            </div>
            <div class="text-wrapper">
              <div class="stat-number">{{ statistics.orderCount || 0 }}</div>
              <div class="stat-label">商城订单</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="never" class="stat-card" style="--card-bg: #17a2b8;">
          <div class="card-content">
            <div class="icon-wrapper">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="text-wrapper">
              <div class="stat-number">¥{{ formatAmount(statistics.totalAmount) || '0.00' }}</div>
              <div class="stat-label">交易金额</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="clearfix">
              <span>最新消息</span>
              <el-button
                  style="float: right; padding: 3px 0"
                  type="text"
                  @click="refreshNews"
                  :loading="newsLoading"
              >
                刷新
              </el-button>
            </div>
          </template>
          <div v-if="newsList.length === 0 && !newsLoading" class="empty-news">
            <el-empty description="暂无最新消息" :image-size="80">
              <el-button type="primary" @click="refreshNews">刷新消息</el-button>
            </el-empty>
          </div>
          <div v-else v-loading="newsLoading">
            <div v-for="news in newsList" :key="news.id" class="text item">
              <el-icon><Warning /></el-icon>
              <span class="news-content">{{ news.content }}</span>
              <span class="news-time">{{ formatTime(news.createTime) }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="clearfix">
              <span>系统信息</span>
            </div>
          </template>
          <div class="system-info">
            <div class="info-item">
              <span class="info-label">系统版本：</span>
              <span class="info-value">v1.2.0</span>
            </div>
            <div class="info-item">
              <span class="info-label">服务器时间：</span>
              <span class="info-value">{{ currentTime }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">在线用户：</span>
              <span class="info-value">{{ statistics.onlineUserCount || 0 }} 人</span>
            </div>
            <div class="info-item">
              <span class="info-label">今日新增用户：</span>
              <span class="info-value">{{ statistics.todayNewUsers || 0 }} 人</span>
            </div>
            <div class="info-item">
              <span class="info-label">今日订单数：</span>
              <span class="info-value">{{ statistics.todayOrders || 0 }} 单</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { User, PriceTag, ShoppingCart, TrendCharts, Warning } from '@element-plus/icons-vue'
import request from '../../util/request.js' // 根据你的项目结构调整路径

// 响应式数据
const statistics = ref({
  userCount: 0,
  productCount: 0,
  orderCount: 0,
  totalAmount: 0,
  onlineUserCount: 0,
  todayNewUsers: 0,
  todayOrders: 0
})

const newsList = ref([])
const currentTime = ref('')
const statisticsLoading = ref(false)
const newsLoading = ref(false)

// 计算属性：欢迎消息
const welcomeMessage = computed(() => {
  const now = new Date()
  const loginTime = now.toLocaleString('zh-CN')
  const loginIP = '192.168.1.110' // 可以从登录信息中获取
  return `欢迎使用后台管理系统(v1.2), 你本次登录时间为${loginTime}, 登录IP:${loginIP}`
})

// 格式化金额
const formatAmount = (amount) => {
  if (!amount) return '0.00'
  return Number(amount).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN')
}

// 更新当前时间
const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleString('zh-CN')
}

// 获取统计数据
const getStatistics = async () => {
  try {
    statisticsLoading.value = true

    // 并发请求多个统计接口
    const requests = [
      request.get('/admin/user/count'),           // 用户数量
      request.get('/admin/categories/count'),        // 商品种类数量
      request.get('/admin/order/count'),          // 订单数量
      /*request.get('/admin/order/totalAmount'),    // 交易总额（如果有的话）*/
    ]

    const responses = await Promise.allSettled(requests)

    // 处理用户数量
    if (responses[0].status === 'fulfilled' && responses[0].value.data.code === 1) {
      statistics.value.userCount = responses[0].value.data.data
    }

    // 处理商品种类数量
    if (responses[1].status === 'fulfilled' && responses[1].value.data.code === 1) {
      statistics.value.productCount = responses[1].value.data.data
    }

    // 处理订单数量（如果接口存在）
    if (responses[2].status === 'fulfilled' && responses[2].value.data.code === 1) {
      statistics.value.orderCount = responses[2].value.data.data
    }

    // 处理交易总额（如果接口存在）
    if (responses[3].status === 'fulfilled' && responses[3].value.data.code === 1) {
      statistics.value.totalAmount = responses[3].value.data.data
    }

  } catch (error) {
  } finally {
    statisticsLoading.value = false
  }
}

// 获取最新消息（模拟数据，可以替换为真实接口）
const getNews = async () => {
  try {
    newsLoading.value = true
    // 模拟数据
    setTimeout(() => {
      newsList.value = [
        {
          id: 1,
          content: '后台管理系统已开通，欢迎使用！',
          createTime: new Date()
        },
        {
          id: 2,
          content: '系统维护通知：今晚21:00-23:00进行系统维护',
          createTime: new Date(Date.now() - 2 * 60 * 60 * 1000)
        },
        {
          id: 3,
          content: '新功能上线：订单管理模块优化完成',
          createTime: new Date(Date.now() - 4 * 60 * 60 * 1000)
        },
        {
          id: 4,
          content: '安全提醒：请定期修改登录密码',
          createTime: new Date(Date.now() - 6 * 60 * 60 * 1000)
        },
        {
          id: 5,
          content: '数据备份成功，系统运行正常',
          createTime: new Date(Date.now() - 8 * 60 * 60 * 1000)
        }
      ]
      newsLoading.value = false
    }, 1000)

  } catch (error) {
    console.error('获取最新消息失败:', error)
    newsLoading.value = false
  }
}

// 刷新消息
const refreshNews = () => {
  getNews()
}

// 定时器
let timer

// 组件挂载时
onMounted(() => {
  console.log('Dashboard 组件挂载，开始加载数据...')

  // 加载数据
  getStatistics()
  getNews()

  // 更新时间
  updateTime()
  timer = setInterval(updateTime, 1000)
})

// 组件卸载时
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
/* 这里只保留 Dashboard 页面自己需要的样式 */
.breadcrumb {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 4px;
}
.welcome-alert {
  margin-bottom: 20px;
}
.stat-cards {
  margin-bottom: 20px;
}
.stat-card .el-card__body {
  padding: 0;
}
.card-content {
  display: flex;
  align-items: center;
  color: white;
}
.icon-wrapper {
  padding: 20px;
  font-size: 40px;
  background-color: var(--card-bg);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px 0 0 4px;
}
.text-wrapper {
  padding: 10px 20px;
  background-color: white;
  color: #333;
  flex-grow: 1;
  text-align: center;
}
.stat-number {
  font-size: 28px;
  font-weight: bold;
}
.stat-label {
  font-size: 14px;
  color: #6c757d;
}
.box-card {
  width: 100%;
}
.text {
  font-size: 14px;
}
.item {
  margin-bottom: 18px;
}
.item:last-child {
  margin-bottom: 0;
}
</style>